<template>
  <a-card>
    <div class="table-page-search-wrapper">
      <a-form class="formArea" layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="规则名称">
              <a-input v-model="searchParams.f_name" placeholder="请输入规则名称" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="创建时间">
              <a-range-picker v-model="createTimes" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="createTimeChange" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="searchParams.f_status" placeholder="请选择状态" allowClear>
                <a-select-option v-for="status in St_enableList" :key="status.value" :value="status.value">
                  {{ status.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button class="btn_primary_color" type="primary" style="margin-left: 20px" @click.stop="search" icon="search">查询</a-button>
            <a-button class="btn_normal_color" icon="reload" style="margin-left: 8px" @click.stop="reset">重置</a-button>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="6" :sm="24">
            <div>
              <a-button class="btn_primary_color" type="primary" style="margin-left: 12px" @click="addRule">新增规则</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 自定义表头组件 -->
    <HEADERDEFINITION ref="headerDefRef" :ucolumns="columns" @f_setColumns="s_setColumns" />
    <div class="headerdefBox">
      <a-tooltip placement="topLeft">
        <template slot="title">
          <span>重置表格</span>
        </template>
        <img @click="resetting()" style="margin-right: 16px" src="@/assets/icons/table/table_refresh.png" alt="重置" />
      </a-tooltip>

      <a-tooltip placement="topLeft">
        <template slot="title">
          <span>设置表格</span>
        </template>
        <img @click="showHeaderDef($event)" src="@/assets/icons/table/table_config.png" alt="表格设置" />
      </a-tooltip>
    </div>

    <a-table
      :scroll="{ x: 1000, y: 550 }"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      rowKey="id"
      @change="tableChange"
      size="middle"
      :bordered="true"
      :rowClassName="rowClassName"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
      </span>
      <div slot="operation" slot-scope="text, record">
        <a-popconfirm
          title="是否更改状态？"
          ok-text="确认"
          cancel-text="取消"
          @confirm="updateStatus(record)"
        >
          <a href="#">{{ record.status === St_enableValue.YES ? '禁用' : '启用' }}</a>
        </a-popconfirm>
        <a-divider type="vertical" />
        <a href="#" @click="editRule(record.id)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm
          title="是否删除这条规则？"
          ok-text="确认"
          cancel-text="取消"
          @confirm="deleteRule(record.id)"
        >
          <a href="#" style="color: red">删除</a>
        </a-popconfirm>
      </div>
    </a-table>
  </a-card>
</template>
<script>
import { St_enableList, St_enableValue } from '@/enumeration/St_enable'
import { deleteSamecaseRule, samecaseRuleList, saveSamecaseRule } from '@/api/correction/crw_rule_samecase'

export default {
  components: {
    HEADERDEFINITION: () => import('@/views/customComponents/headerDefinition.vue')
  },
  computed: {
    St_enableValue () {
      return St_enableValue
    },
    St_enableList () {
      return St_enableList
    }
  },
  data() {
    return {
      loading: false,
      columns: [
        {
          title: '序号',
          width: 80,
          key: 'index',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '规则名称',
          dataIndex: 'name',
          key: 'name',
          align: 'left',
          ellipsis: true,
          customRender: (text) => <a-tooltip placement="topLeft" title = {text} >{text}</a-tooltip>
        },
        {
          title: '空间距离（米）',
          dataIndex: 'range_space',
          key: 'range_space',
          align: 'left'
        },
        {
          title: '时间距离（分）',
          dataIndex: 'range_time',
          key: 'range_time',
          align: 'left'
        },
        {
          title: '人员姓名',
          dataIndex: 'pernames',
          key: 'pernames',
          align: 'left'
        },
        {
          title: '状态',
          dataIndex: 'status_text',
          key: 'status_text',
          align: 'left'
        },
        {
          title: '创建时间',
          dataIndex: 'createtime',
          key: 'createtime',
          align: 'left'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 180,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      dataSource: [],
      createTimes: [],
      searchParams: {
        f_name: '',
        f_status: undefined,
        f_createtime: undefined,
        f_createtime_01: undefined
      },
      queryParams: {
        f_name: '',
        f_createtime: undefined,
        f_createtime_01: undefined,
        f_status: undefined,
        pageNumber: 1,
        pageSize: 20
      },
      pagination: {
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      }
    }
  },
  methods: {
    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    // 重置表头方法
    resetting () {
      this.$refs.headerDefRef.f_resetting()
    },
    // 子组件回调函数, 重置表头
    s_setColumns (columns) {
      this.columns = columns
    },
    // 显示自定义表头组件
    showHeaderDef (e) {
      this.$refs.headerDefRef.f_init(e)
    },
    search () {
      console.log(this.$router)
      this.queryParams.pageNumber = 1
      this.queryParams.f_status = this.searchParams.f_status
      this.queryParams.f_name = this.searchParams.f_name
      this.queryParams.f_createtime = this.searchParams.f_createtime
      this.queryParams.f_createtime_01 = this.searchParams.f_createtime_01
      this.loadData(this.queryParams)
    },
    reset () {
      this.searchParams = this.$options.data().searchParams
      this.queryParams = this.$options.data().queryParams
      this.pagination = this.$options.data().pagination
      this.createTimes = []
      this.search()
    },
    createTimeChange (dates) {
      console.log(dates)
      if (dates.length > 0) {
        this.searchParams.f_createtime = dates[0]
        this.searchParams.f_createtime_01 = dates[1]
      } else {
        this.searchParams.f_createtime = undefined
        this.searchParams.f_createtime_01 = undefined
      }
    },
    tableChange (pagination) {
      this.queryParams.pageNumber = pagination.current
      this.queryParams.pageSize = pagination.pageSize
      this.pagination.pageSize = pagination.pageSize
      this.pagination.current = pagination.current
      this.loadData(this.queryParams)
    },
    async loadData (params) {
      this.loading = true
      const { code, data } = await samecaseRuleList(params)
      if (code !== 0) {
        this.loading = false
        this.$message.error('查询数据失败!')
        return
      }
      this.dataSource = data.records
      this.pagination.total = data.total
      this.pagination.current = data.current
      this.pagination.pageSize = data.size
      this.loading = false
    },
    addRule () {
      this.$router.push({
        path: '/CorrectSameCaseDetail',
        query: {
          params: JSON.stringify(this.queryParams),
          type: 'samecase'
        }
      })
    },
    editRule (ruleId) {
      this.$router.push({
        path: '/CorrectSameCaseDetail',
        query: {
          params: JSON.stringify(this.queryParams),
          type: 'samecase',
          ruleId: ruleId
        }
      })
    },
    async updateStatus (record) {
      record.status = (record.status === St_enableValue.YES ? St_enableValue.NO : St_enableValue.YES)
      const { code } = await saveSamecaseRule(record)
      if (code !== 0) {
        this.$message.error('更改规则状态失败')
        return
      }
      this.search()
    },
    async deleteRule (ruleId) {
      const { code } = await deleteSamecaseRule(ruleId)
      if (code !== 0) {
        this.$message.error('删除规则失败')
        return
      }
      this.search()
    }
  },
  created () {
    if (this.$route.query.params) {
      this.queryParams = JSON.parse(this.$route.query?.params)
      this.pagination.current = this.queryParams.pageNumber
      this.pagination.pageSize = this.queryParams.pageSize
      this.searchParams.f_name = this.queryParams.f_name
      this.searchParams.f_status = this.queryParams.f_status
      this.searchParams.f_createtime = this.queryParams.f_createtime
      this.searchParams.f_createtime_01 = this.queryParams.f_createtime_01
      this.createTimes = [this.searchParams.f_createtime,this.searchParams.f_createtime_01]
    }
    this.loadData(this.queryParams)
  }
}
</script>
<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';

.formArea {
  margin-bottom: 30px;
}
.headerdefBox img {
  height: 20px;
  width: 20px;
}
.headerdefBox {
  margin: 0 10px 10px 0;
  display: flex;
  justify-content: end;
}
</style>
